//
//  ZHomeViewController.m
//  shopSN
//
//  Created by yisu on 16/6/12.
//  Copyright © 2016年 yisu. All rights reserved.
//

#import "ZHomeViewController.h"

#import "ZYSLoginViewController.h"//测试登录
#import "ZCenterMemberCertificateViewController.h"
#import "ZGoodsListViewController.h" //商品列表
#import "ZListForGoodsViewController.h"  //会员商城商品列表页面

#import "ZGoodsSearchViewController.h"//商品搜索
#import "ZCategoryViewController.h" //分类页面
#import "ZCommonGoodsInfoViewController.h"//会员商品信息页面
#import "ZScanViewController.h"//扫描二维码

//sub
#import "ZHomeGridHeader1.h"//顶部广告和专区选择
#import "ZHomeCategoryCell.h"//顶部分类选择
#import "ZHomeGridFooter1.h"//底部分割
#import "ZHomeGridGoodsCell.h"//商品展示cell
#import "ZHomeGridHeader2.h"//商品展示 标题
#import "ZHomeGridFooter2.h"//商品展示 广告
#import "ZHomeGirdGoodsFooter2.h"//会员商城商品展示 广告
#import "ZHomeRecommendCell.h"//推荐内容cell
#import "ZHomeGridHeader3.h"//推荐内容 标题

#import "ZHomeheader.h"

@interface ZHomeViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,ZHomeGridHeader1Delegate, UITextFieldDelegate,ZHomeGridHeader3Delegate>
{
    /** 主页面 collectionView */
    UICollectionView *_grid;
    UITextField *searchTF;
    
    //判断是否为会员商品
    //BOOL _isGoods;
    
    //顶部内容  广告图片 专区标题
    NSArray *_headerTitleArray;//
    NSArray *_headerImageArray;//
    
    
    
    NSArray *_categoryTitleArray;//分类标题数组
    NSArray *_categoryIVArray;//分类图片数组
    
    
    //中间推荐内容
    NSArray *_recommendTitleArray;
    NSArray *_recommendImageArray;
    
    
    NSArray *bannerArray;// instead headerImageArray
    //NSArray *classArray;// instead categoryIVArray
    NSArray *hotArray; //热门商品
    NSArray *centerArray;//隐藏类别下方的center商品图片
    NSArray *classPageArray;//会员旅游使用该数据

    NSMutableArray *classArray;// instead categoryIVArray
    NSArray *_currentClassArray;//当前数据
    NSArray *_selectArray; //选择有图片的数据
    int _currentPage;//页数
    
    
    
    NSArray *_sectionArray;//内容列表标题数组
    NSArray *_categorySectionArray;//分类页面 主类数组
    NSArray *_rowTitleArray;//分类页面 内容标题数组
    
    NSArray *_goodsRowTitleArray;//会员商品二级分类标题
    NSArray *_travelRowTitleArray;//会员旅游二级分类标题
    
    
    
    
}

@property (nonatomic, assign) BOOL isGoods;



@property (nonatomic, strong) NSMutableArray *goodsTopCategorys;//会员商品一级分类数组
@property (nonatomic, strong) NSMutableArray *goodsTwoCategorys;//会员商品二级分类数组


@property (strong,nonatomic) UIButton *loginBtn;//登录按钮

@property (strong,nonatomic) UIButton *saoBtn;//二维码按钮

@end




@implementation ZHomeViewController

#pragma mark - ==== 页面设置 =====

- (void)viewWillAppear:(BOOL)animated {
    //隐藏 导航栏
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = NO;
    //设置 状态栏背景和字体颜色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    if ([UdStorage getObjectforKey:Userid]) {
        _loginBtn.hidden = YES;
        _saoBtn.hidden= NO;
    }else{
        _loginBtn.hidden = NO;
        _saoBtn.hidden = YES;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    //取消隐藏 导航栏
    self.navigationController.navigationBarHidden = NO;
    
    //恢复状态栏 背景和字体颜色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}



#pragma mark - ===== 页面设置 =====
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //self.view.backgroundColor = HEXCOLOR(0xf0f0f0);
    //初始 数据
    _currentPage = 1;
    classArray = [NSMutableArray array];
    _isGoods = YES;
    
    
    
    [self getData];//获取数据
    
    [self initNavi];// 自定义导航栏
    
    [self initMainView];//初始化主页面视图
    
    
}


#pragma mark - 自定义导航栏
// 自定义导航栏
- (void)initNavi {
    BaseView *topView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, __kWidth, 64)];
    //topView.backgroundColor = HEXCOLOR(0xffffff);
    topView.backgroundColor = __DefaultColor;
    [self.view addSubview:topView];
    
    
    UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 25, __kWidth, 40)];
    //subView.backgroundColor = __DefaultColor;
    [topView addSubview:subView];
    

    
    //左侧分类 按钮
    UIButton *feileiBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, 10, 20, 20)];
    //feileiBtn.backgroundColor = __TestOColor;
    [feileiBtn setBackgroundImage:MImage(@"feilei") forState:BtnNormal];
    //feileiBtn.backgroundColor = [UIColor clearColor];
    [feileiBtn addTarget:self action:@selector(feileiAction) forControlEvents:BtnTouchUpInside];
    [subView addSubview:feileiBtn];
    
    //右侧登录按钮
    _loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(__kWidth-15-30, 10, 30, 20)];
    //loginBtn.backgroundColor = __TestOColor;
    _loginBtn.titleLabel.font = MFont(14);
    [_loginBtn setTitle:@"登录" forState:BtnNormal];
    [_loginBtn setTitleColor:HEXCOLOR(0xffffff) forState:BtnNormal];
    [_loginBtn addTarget:self action:@selector(loginAction) forControlEvents:BtnTouchUpInside];
    [subView addSubview:_loginBtn];

    
    
//    //右侧扫二维码按钮
    _saoBtn = [[UIButton alloc] initWithFrame:CGRectMake(__kWidth-15-20, 10, 20, 20)];
    //saoBtn.backgroundColor = __TestOColor;
    [_saoBtn setImage:MImage(@"sys_w.png") forState:BtnNormal];
    [_saoBtn addTarget:self action:@selector(saoAction) forControlEvents:BtnTouchUpInside];
    [subView addSubview:_saoBtn];

    

    if ([UdStorage getObjectforKey:Userid]) {
        _loginBtn.hidden = YES;
        _saoBtn.hidden= NO;
    }else{
        _loginBtn.hidden = NO;
        _saoBtn.hidden = YES;
    }

    //中间搜索框
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(CGRectXW(feileiBtn)+20, 5, CGRectW(subView)-CGRectW(feileiBtn)-CGRectW(_loginBtn)-30-40, 30)];
    searchView.backgroundColor = HEXCOLOR(0xffffff);
    searchView.layer.cornerRadius = 5;
    [subView addSubview:searchView];
    [self createSearchSubView:searchView];
    
    
    
 
    
}


//自定义搜索视图内部控件
- (void)createSearchSubView:(UIView *)btnView {
    

    //searchIV
    UIImageView *searchIV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 7.5, 15, 15)];
    searchIV.image = MImage(@"sousuo");
    //searchIV.backgroundColor = __TestOColor;
    [btnView addSubview:searchIV];
    
    //searchTF
    searchTF = [[UITextField alloc] initWithFrame:CGRectMake(CGRectXW(searchIV)+5, 5, CGRectW(btnView)-CGRectW(searchIV)-25, CGRectH(btnView)-10)];
    [btnView addSubview:searchTF];
    //searchTF.backgroundColor = __TestGColor;
    searchTF.delegate = self;
    searchTF.font = MFont(14);
    searchTF.textColor = HEXCOLOR(0x333333);
    searchTF.clearButtonMode = UITextFieldViewModeWhileEditing;//小叉子
    searchTF.keyboardType = UIKeyboardTypeWebSearch;//web搜索模式
    searchTF.placeholder = @"搜索内容";
    
    
    
}



#pragma mark - 主视图初始化
//初始化主页面视图
- (void)initMainView {
    
    //背景视图
    UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, __kWidth, __kHeight-64)];
    mainView.backgroundColor = HEXCOLOR(0xffffff);
    [self.view addSubview:mainView];
    
    
    //collectionView
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    CGRect frame = CGRectMake(0, 0, __kWidth, __kHeight-64-50);
    _grid = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
    [mainView addSubview:_grid];
    
    _grid.backgroundColor = HEXCOLOR(0xffffff);
    //    _grid.backgroundColor = HEXCOLOR(0xdedede);
    _grid.dataSource = self;
    _grid.delegate   = self;
    
    //注册cell和ReusableView  必须通过注册class方式 实现重用
    //section 0
    [_grid registerClass:[ZHomeCategoryCell class] forCellWithReuseIdentifier:@"ChooseGetegoryCell"];//选择类别
    [_grid registerClass:[ZHomeGridHeader1 class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header1"];//顶部滚动图片和专区选择
    [_grid registerClass:[ZHomeGridFooter1 class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"Footer1"];//底部分割
    [_grid registerClass:[ZHomeGirdGoodsFooter2 class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"GoodsFooter2"];//加滚动字幕和广告图片 底部分割
    [_grid registerClass:[ZHomeheader class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"GoodsAD"];
    //section1 热销商品
    [_grid registerClass:[ZHomeRecommendCell class] forCellWithReuseIdentifier:@"RecommendCell"];//推荐内容cell
    [_grid registerClass:[ZHomeGridHeader3 class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header3"];//推荐内容标题
 
    
    //section3
    [_grid registerClass:[ZHomeGridGoodsCell class] forCellWithReuseIdentifier:@"GoodsCell"];//会员商品展示cell
    [_grid registerClass:[ZHomeGridHeader2 class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header2"];//顶部广告和专区选择
    [_grid registerClass:[ZHomeGridFooter2 class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"Footer2"];//底部广告
    
    
    //刷新控件
    //[_grid addHeaderWithTarget:self action:@selector(refreshGoodsData)];//下拉刷新
    [_grid addFooterWithTarget:self action:@selector(loadMoreGoodsData)];//上拉加载更多
    
    
    
}





#pragma mark - ===== 按钮方法 btnAction ====
//
- (void)feileiAction {
//    NSLog(@"跳转至 商品列表页面");
//    ZGoodsListViewController *vc = [[ZGoodsListViewController alloc] init];
    
    NSLog(@"跳转至 分类页面");
    ZCategoryViewController *vc = [[ZCategoryViewController alloc] init];
    
    //测试数据
    vc.categoryArr    = _categorySectionArray;
    //vc.subCategoryArr = _subSectionArray;
    vc.rowTitleArr    = _rowTitleArray;

    vc.isGoods = _isGoods;
    [self.navigationController pushViewController:vc animated:YES];
    
}

//跳转登录页面
- (void)loginAction {
    NSLog(@"跳转至 登录页面");
    ZYSLoginViewController *vc = [[ZYSLoginViewController alloc]init];

    [self.navigationController pushViewController:vc animated:YES];
}

//跳转登录页面
- (void)saoAction {
    NSLog(@"跳转至 扫二维码页面");
    
    ZScanViewController *vc = [[ZScanViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


//跳转商品搜索页面
- (void)searchAciton {
    NSLog(@"跳转至 搜索商品页面");
    ZGoodsSearchViewController *vc = [[ZGoodsSearchViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

//跳转更多 热门活动页面
- (void)moreOutDoodrBtn:(UIButton *)btn {
    NSLog(@"跳转至%d=== %@页面",(btn.tag-210),[NSString stringWithFormat:@"%@",_sectionArray[btn.tag-210]]);
    
    
    
}




#pragma mark - UICollectionView DataSource and Delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    //选择分类
    if (section == 0) {
//        return _categoryTitleArray.count;//test
        return classPageArray.count;//loadData
    }
    //热销商品 推荐内容
  
//    if (section == 1 ) {
//        return 2;
//    }

    if (section == 1) {
        return 4;
    }

    //展示内容
    else{
        
        //return 6;//测试数据
        return classArray.count;
        
        
        //添加判断 如果没有图片隐藏该行
//        for (int i= 0; i<classArray.count; i++) {
//            ZHomePicModel *pic = [[ZHomePicModel alloc] init];
//            pic = classArray[i];
//            if ([pic.classUrl isEqualToString:@"0"] || IsNilString(pic.classUrl)) {
//                
//            }
//        }
        

    }
    
    
    
}

//
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    UICollectionViewCell *gridCell = nil;
    //顶部类别
    if (indexPath.section == 0) {
        
        ZHomeCategoryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ChooseGetegoryCell" forIndexPath:indexPath];
         //test
//        cell.categoryIV.image = MImage(_categoryIVArray[indexPath.row]);
//        cell.categoryLb.text = _categoryTitleArray[indexPath.row];
//
        //loadData
        ZHomePicModel *pic = [[ZHomePicModel alloc] init];
        pic = classPageArray[indexPath.row];
        cell.categoryLb.text = pic.className;
        NSString *urlStr = [NSString stringWithFormat:@"%@%@",HomeClassUrl,pic.classUrl];
        //NSLog(@"classPageUrl:%@",urlStr);
        [cell.categoryIV sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:MImage(@"icon09.png")];
//
        gridCell = cell;
    }
//    //热销商品(增加假数据团购)
//    else if (indexPath.section == 1) {
//        ZHomeRecommendCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RecommendCell" forIndexPath:indexPath];
//        
//        gridCell = cell;
//        //test
//        //cell.recommendIV.image = MImage(@"pic08");
//        //cell.recommendIV.image = MImage(_recommendImageArray[indexPath.row]);
//        //NSLog(@"x:%f===%f",cell.frame.origin.x, cell.frame.origin.y);
//        //NSLog(@"w:%f===h:%f",cell.frame.size.width, cell.frame.size.height);
//        
//        //loadData
//        ZHomePicModel *pic = [[ZHomePicModel alloc] init];
//        pic = hotArray[indexPath.row];
//        NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HomeADUrl,pic.hotUrl];
//        [cell.recommendIV sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:MImage(@"pic09.png")];
//        //cell.recommendIV.contentMode = UIViewContentModeScaleAspectFit;
//        
//    }
    else if (indexPath.section == 1) {
        ZHomeRecommendCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RecommendCell" forIndexPath:indexPath];

        gridCell = cell;
        //test
        //cell.recommendIV.image = MImage(@"pic08");
        //cell.recommendIV.image = MImage(_recommendImageArray[indexPath.row]);
        //NSLog(@"x:%f===%f",cell.frame.origin.x, cell.frame.origin.y);
        //NSLog(@"w:%f===h:%f",cell.frame.size.width, cell.frame.size.height);

        //loadData
        ZHomePicModel *pic = [[ZHomePicModel alloc] init];
        pic = hotArray[indexPath.row];
        NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HomeADUrl,pic.hotUrl];
        [cell.recommendIV sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:MImage(@"pic09.png")];
        //cell.recommendIV.contentMode = UIViewContentModeScaleAspectFit;

    }
    //展示内容
    else {
        
        ZHomeGridGoodsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GoodsCell" forIndexPath:indexPath];
        gridCell = cell;

        
        
        ZHomePicModel *pic = [[ZHomePicModel alloc] init];
        pic = classArray[indexPath.row];
        NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HomeClassUrl,pic.classUrl];
        [cell.goodsIV sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:MImage(@"pic11.png")];
        
        //添加判断 如果没有图片隐藏该行
        if ([pic.classUrl isEqualToString:@"0"] || IsNilString(pic.classUrl)) {
            [gridCell removeFromSuperview];
        }
        
    }
     [collectionView bringSubviewToFront:gridCell];
    
    return gridCell;
    
}




// header和footer
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableView = nil;
    
    if (indexPath.section == 0) {
        //选择类别 广告
        if (kind == UICollectionElementKindSectionHeader) {
            ZHomeGridHeader1 *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header1" forIndexPath:indexPath];
            
            headerView.isGoods = _isGoods;
            //提供数据
            //[headerView getDataWithTitleArray:_headerTitleArray andImageArray:_headerImageArray];//test
            [headerView getDataWithTitleArray:_headerTitleArray andImageArray:bannerArray];
//            if (_isGoods) {
//                headerView.scrollView.hidden = NO;
//                headerView.footerLb.hidden = NO;
//            }else{
                headerView.scrollView.hidden = YES;
                headerView.footerLb.hidden = YES;
//            }

            reusableView = headerView;
            headerView.delegate = self;
            
            
        }
        //会员商城隐藏后 所使用的center商品图片
        if (kind == UICollectionElementKindSectionFooter) {
            //会员商城隐藏后 所使用的center商品图片
//            ZHomeGridFooter2 *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"Footer2" forIndexPath:indexPath];
            ZHomeheader *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"GoodsAD" forIndexPath:indexPath];
                
            //load centerData
            ZHomePicModel *pic = [[ZHomePicModel alloc] init];
            pic = centerArray[0];
                
            NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HomeADUrl,pic.centerUrl];
            NSLog(@"imageUrl:%@",imageUrl);
            [footerView.commonGoodsFooterCenterIV sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:MImage(@"pic11.png")];
                
            reusableView = footerView;

            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(centerPicTapAction)];
            [reusableView addGestureRecognizer:tap];
            
            
        }
        
    }
    
//    else if (indexPath.section == 1) {
//        if (kind == UICollectionElementKindSectionHeader) {
//            ZHomeGridHeader3 *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header3" forIndexPath:indexPath];
//            reusableView = headerView;
//            headerView.delegate =self;
//            
//            headerView.recommendTitleLb.text = @"团购商品";//注意数组
//            
//        }
//        if (kind == UICollectionElementKindSectionFooter) {
//            ZHomeGridFooter2 *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"Footer2" forIndexPath:indexPath];
//            footerView.commonGoodsFooterView.hidden = YES;
//            reusableView = footerView;
//        }
//    }
//
    else if (indexPath.section == 1) {
        if (kind == UICollectionElementKindSectionHeader) {
            ZHomeGridHeader3 *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header3" forIndexPath:indexPath];
            reusableView = headerView;
            headerView.moreBtn.hidden = YES;

            headerView.recommendTitleLb.text = _recommendTitleArray[0];//注意数组

        }
        if (kind == UICollectionElementKindSectionFooter) {
            ZHomeGridFooter2 *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"Footer2" forIndexPath:indexPath];
            footerView.commonGoodsFooterView.hidden = YES;
            reusableView = footerView;
        }
    }

    
    
    
    return reusableView;
}





//内容距离屏幕边缘的距离 参数顺序是top,left,bottom,right
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    //选择类别
    if (section == 0) {
        return UIEdgeInsetsMake(0, 2.0f, 2.f, 0);
    }
    
    //内容展示
//    if (section == 1) {
//        
//        return UIEdgeInsetsMake(1.0f, 0, 0, 0);
//    }
    
    return UIEdgeInsetsZero;
    
    
}

//x 间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

//y 间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    //选择类别
    return 0;
}

//item 宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    //选择类别 横向5 纵向2
    if (indexPath.section == 0) {
//        if (_isGoods == YES) {
//            return CGSizeZero;
//        }
        return CGSizeMake((CGRectW(_grid)-4-4-1)/5, CGRectW(_grid)/5);
        //return CGSizeMake((CGRectW(_grid)-4)/5, CGRectW(_grid)/5);
        
    }
    
    //热销商品
    else if (indexPath.section == 1){
     return CGSizeMake((CGRectW(_grid)-1)/2, (CGRectW(_grid))/2-67);
    }
////    热销商品 
//    else if(indexPath.section == 2) {
//        
//        return CGSizeMake((CGRectW(_grid)-1)/2, (CGRectW(_grid))/2-67);
//        //return CGSizeMake((CGRectW(_grid)-1)/2, (CGRectW(_grid)-30)/2);
//    }

    //展示内容 横向1
    else{
        
//        if (_isGoods == YES) {
//            //会员商品展示
//            return CGSizeMake(CGRectW(_grid), 330);
//        }else{
//            //会员旅游展示
//            return CGSizeMake((CGRectW(_grid)-1)/2, (CGRectW(_grid))/2);
//        }
        
        return CGSizeMake(CGRectW(_grid), 240);
    }
    
    //return CGSizeMake(0, 0);
    
}





//header 宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    //滚动视图和专区选择视图
    if (section == 0) {
//        if (_isGoods) {
//            if (__kHeight > __k5Height) {
//                return CGSizeMake(__kWidth, 335);
//            }
//            return CGSizeMake(__kWidth, 300);
//
//        }else{
//            if (__kHeight > __k5Height) {
//                return CGSizeMake(__kWidth, 200);
//            }
//            return CGSizeMake(__kWidth, 175);
            
            if (__kHeight > __k5Height) {
                return CGSizeMake(__kWidth, 170);
            }
            return CGSizeMake(__kWidth, 155);
//        }


        
    }
    else if (section == 1) {
        //return CGSizeMake(__kWidth, 30); 修改标题高度
        return CGSizeMake(__kWidth, 40);
    }
    
    return CGSizeZero;
}


//footer 宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    //分割

    if (section == 0) { //顶部类别下方 center商品图片
        return CGSizeMake(__kWidth, 130);
    }
    else if (section == 1) {
        return CGSizeMake(__kWidth, 15);

    }
    return CGSizeZero;
}



//选中触发方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"选择的是: 第%ld组 第%ld个",(long)indexPath.section, (long)indexPath.row);
    
    //类别选择
    if (indexPath.section == 0) {
//        if (_isGoods) {
//            //取消该内容
//        }else{
            ZHomePicModel *pic = [[ZHomePicModel alloc] init];
            pic = classPageArray[indexPath.row];
            NSLog(@"choose:%@===%@",pic.classID,pic.className);
            [self pushListViewForGoodsControllerWithCategoryID:pic.classID];
//        }
    }
    
    //hot 热门推荐内容
    if (indexPath.section == 1) {
        
        //NSLog(@"热门推荐内容");
        //会员商品
        if (_isGoods) {
            ZHomePicModel *pic = [[ZHomePicModel alloc] init];
            pic = hotArray[indexPath.row];
            //            NSString *linkStr = pic.linkUrl;
            //            NSLog(@"linkStr:%@==strlength:%d",linkStr, linkStr.length);
            NSRange range = [pic.linkUrl rangeOfString:@"id="];
            NSString *str = [pic.linkUrl substringFromIndex:range.location+range.length];
            NSString *goodID = str;
            
            ZCommonGoodsInfoViewController *vc = [[ZCommonGoodsInfoViewController alloc] init];
            vc.comGoodsID = goodID;
//               vc.comGoodsID = @"767";
            [self.navigationController pushViewController:vc animated:YES];
            
        }
    }
    
    
    
    //内容展示
    if (indexPath.section == 2) {
        ZHomeGridGoodsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GoodsCell" forIndexPath:indexPath];
        NSLog(@"%@",cell.goodsTypeLb.text);
        
        //原商品列表页面
//        ZGoodsListViewController *vc = [[ZGoodsListViewController alloc] init];
//        vc.itemName = cell.goodsTypeLb.text;
//        [self.navigationController pushViewController:vc animated:YES];
        
        
        //新商品列表分类页面
        ZHomePicModel *pic = [[ZHomePicModel alloc] init];
        pic = classArray[indexPath.row];
        //NSLog(@"跳转会员商品列表信息: id=%@ name=%@",pic.classID, pic.className);
        
        if (_isGoods) {
            //会员商城
            ZListForGoodsViewController *goodsVC = [[ZListForGoodsViewController alloc] init];
            goodsVC.subCategoryID   = pic.classID;
            goodsVC.subCategoryName = pic.className;
            [self.navigationController pushViewController:goodsVC animated:YES];
            
        }
    }
    
    
}


#pragma mark - ===== 刷新控件设置内容 =====
#pragma mark - 上拉加载更多
- (void)collectionViewFootLoadAction {
    
    [self loadMoreGoodsData];
}


//加载更多商品
- (void)loadMoreGoodsData {
    NSLog(@"商品搜索页面 加载更多");
    [_grid footerEndRefreshing];
    if (_currentClassArray.count == 10) {
        _currentPage++;
        if (_isGoods) {
            [self requestHomeGoodsMainData];
        }
    }else{
        _grid.footerRefreshingText = @"没有更多数据了 ...";
        _grid.footerReleaseToRefreshText = @"没有更多数据了 ...";
    }
    
    
    
}


#pragma mark - 下拉刷新数据
- (void)refreshGoodsData {
    NSLog(@"商品搜索页面 下拉刷新");
    [_grid headerEndRefreshing];
    //初始化 数据
    _currentPage = 1;
    [classArray removeAllObjects];
    if (_isGoods) {
        [self requestHomeGoodsMainData];
    }
}






#pragma mark ===== 首页点击分类图片跳转商品列表页面 =====
//会员商城跳转
- (void)pushListViewForGoodsControllerWithCategoryID:(NSString *)ca_ID  {
    //*** 使用一级分类全数据接口
    ZListForGoodsViewController *goodsVC = [[ZListForGoodsViewController alloc] init];
    goodsVC.mainCategoryID = ca_ID;
    [self.navigationController pushViewController:goodsVC animated:YES];
    
    //115.159.146.202/api/goods.php?action=two_level_class&id=16
    //NSMutableArray *mutArr = [NSMutableArray array];
//    [ZHttpRequestService POSTGoods:@"two_level_class" withParameters:@{@"id":ca_ID} success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
//        if (succe) {
//            
//            NSArray *array = [Parse parseSubCategory:jsonDic[@"data"]];
//            //NSLog(@"%@",array);
//            ZSubCategory *sub = array[0];
//            
//            ZListForGoodsViewController *goodsVC = [[ZListForGoodsViewController alloc] init];
//            goodsVC.subCategoryID = sub.subCategoryID;
//            goodsVC.subCategoryName = sub.subCategoryName;
//            [self.navigationController pushViewController:goodsVC animated:YES];
//            
//            
//        }else{
//            NSString *message = jsonDic[@"message"];
//            [SXLoadingView showAlertHUD:message duration:SXLoadingTime];
//            
//        }
//    } failure:^(NSError *error) {
//        [SXLoadingView showAlertHUD:@"请求失败" duration:SXLoadingTime];
//        
//    } animated:NO withView:nil];

    

    
}


#pragma mark - 点击会员商城 center图片触发跳转
- (void)centerPicTapAction {
    
    //NSLog(@"跳转会员商品列表页面");
    
    ZHomePicModel *pic = [[ZHomePicModel alloc] init];
    pic = centerArray[0];
    NSString *linkStr = pic.linkUrl;
    //NSLog(@"linkStr:%@==strlength:%d",linkStr, linkStr.length);
    if (linkStr.length < 64) {
        //[SXLoadingView showAlertHUD:@"当前数据异常" duration:SXLoadingTime];
    }else{
        
        NSRange range = [pic.linkUrl rangeOfString:@"id="];
        NSString *str = [pic.linkUrl substringFromIndex:range.location+range.length];
        NSString *classID = str;
        NSLog(@"centerPic:%@",classID);
        
        
        if (_isGoods) {
            //会员商城
            ZListForGoodsViewController *goodsVC = [[ZListForGoodsViewController alloc] init];
            goodsVC.subCategoryID   = classID;
            //goodsVC.subCategoryName = pic.className;
            [self.navigationController pushViewController:goodsVC animated:YES];
            
        }

    }
    
    
}


#pragma mark - ===== 获取数据 =====



- (void)getData {
    
    
    
    
    //测试数据
    
    //1 顶部分类选择 图片和标题
    _categoryIVArray = @[@"icon01", @"icon02", @"icon03", @"icon04", @"icon05", @"icon06", @"icon07", @"icon08", @"icon09", @"icon10"];
    
    _categoryTitleArray = @[@"箱包用品", @"女装内衣", @"婴儿食品", @"电子产品", @"用品玩具", @"美妆个护", @"食品烟酒", @"居家百货", @"休闲娱乐", @"热门分类 "];
    
    
    //2 商品展示 标题名称
    _sectionArray = @[@"热门分类",@"全球购",@"奶粉纸尿裤",@"童装童鞋",@"食品烟酒",@"用品玩具",@"女装内衣",@"鞋包佩饰",@"美妆个护",@"居家百货"];
    
    
    //4 头部广告图片 专区标题
    //_headerTitleArray = @[@"会员商品", @"会员旅游", @"合伙人商品", @"合伙人旅游"];
    _headerTitleArray = @[@"会员商城", @"会员旅游"];
    _headerImageArray = @[@"banner01", @"banner02", @"banner01", @"banner02"];
    
    
    //中间推荐内容
    _recommendTitleArray = @[@"热销商品"];
    _recommendImageArray = @[@"pic09", @"pic09", @"pic09", @"pic09"];
    
    //会员商品 分类页面数据请求
    [self goodsCategoryDataRequest];
    
    
    
    //会员商品 首页数据请求
    [self requestHomeGoodsMainData];
    
    
    
}

//会员商品 分类页面数据请求
- (void)goodsCategoryDataRequest {
    _goodsTopCategorys = [NSMutableArray array];
    _goodsTwoCategorys = [NSMutableArray array];
    //会员商品一级分类数据请求
    [self goodsTopGetegoryRequest];
    
    
    
}



// 会员商品一级分类请求
- (void)goodsTopGetegoryRequest {
    //NSMutableArray *mutArray = [NSMutableArray array];
    //115.159.146.202/api/goods.php?action=top_category
    
    [ZHttpRequestService POSTGoods:@"Goods" withParameters:nil success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            [SXLoadingView hideProgressHUD];
            _goodsTopCategorys = [Parse parseCategory:jsonDic[@"data"]];
            //NSLog(@"%@",_goodsTopCategorys);
            
            ZCategory *category = [[ZCategory alloc] init];
            category = _goodsTopCategorys[0];
            //二级分类数据请求
            [self goodsSubCategoryRequest:category.categoryID withSubCategory:category.subCategory];
            
        }else{
            NSString *message = jsonDic[@"message"];
            [SXLoadingView showAlertHUD:message duration:2];
            
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"查询失败" duration:SXLoadingTime];
        //NSLog(@"%@",error);
    } animated:NO withView:nil];
    
    
 
    
}

// 会员商品二级分类请求
- (void)goodsSubCategoryRequest:(NSString *)categoryID withSubCategory:(NSMutableArray *)subCategory {
    //115.159.146.202/api/goods.php?action=two_level_class&id=16
    NSMutableArray *mutArr = [NSMutableArray array];
    [ZHttpRequestService POSTGoods:@"/Goods/twoClassData" withParameters:@{@"id":categoryID} success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            NSArray *data=jsonDic[@"data"];
            for (NSDictionary *dic in data) {
                
                NSString *className = [Utils getTextStrByText:dic[@"class_name"]];
                [mutArr addObject:className];
                
            }
            _goodsTwoCategorys = [Parse parseSubCategory:jsonDic[@"data"]];
            
            
            //NSLog(@"subCategory:%@",_goodsTwoCategorys);
            //NSLog(@"mutArr:%@",mutArr);
            
            //3 分类页面 主类列表 内容名称
            _categorySectionArray = _goodsTopCategorys;
            _rowTitleArray = mutArr;
            
            //代理方法
            [self.delegate sendValueToMainVCWithMainSectionArray:_categorySectionArray andRowArray:_rowTitleArray andIsGoods:_isGoods];
            
        }else{
            NSString *message = jsonDic[@"message"];
            [SXLoadingView showAlertHUD:message duration:SXLoadingTime];
            
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"请求失败" duration:SXLoadingTime];
        
    } animated:NO withView:nil];
}


#pragma mark - 首页会员商城 主数据请求
//首页会员商城 主数据请求
- (void)requestHomeGoodsMainData {

    [ZHttpRequestService GETHome:@"index/" withParameters:nil success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            
            [SXLoadingView hideProgressHUD];
            
            bannerArray = [Parse parseHomeGoodsBannerData:jsonDic[@"data"][@"banner"]];

            
            centerArray = [Parse parseHomeGoodsCenterData:jsonDic[@"data"][@"center"]];
            
            hotArray = [Parse parseHomeGoodsHotData:jsonDic[@"data"][@"hot"]];
            
            
            NSArray *array = [Parse parseHomeGoodsClassData:jsonDic[@"data"][@"clas"]];
            _currentClassArray = array;
            [classArray addObjectsFromArray:array];
            classPageArray = array;

            [_grid reloadData];
            
        }else{
            
            [SXLoadingView showAlertHUD:@"当前数据异常" duration:SXLoadingTime];
            
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"请求失败" duration:SXLoadingTime];
    } animated:NO withView:nil];
    
    
    
}


#pragma mark - ===== ZHomeGridHeader3Delegate =====
-(void)lookmore:(UIButton *)sender{
    NSLog(@"查看更多");
}


#pragma mark - ===== ZHomeGridHeader1 Delegate =====
//实现专区选择
- (void)choosePrefectureButton:(UIButton *)button withIndex:(NSInteger)index withChooseArray:(NSArray *)array {
    
    NSLog(@"选择第%d项 %@",index+1,[NSString stringWithFormat:@"%@",array[index]]);
    
    
    
    if (button.tag == 200 || button.tag == 202) {
        _isGoods = YES;
        [searchTF resignFirstResponder];//移除键盘
        //0 头部广告图片
        _headerImageArray = @[@"banner01", @"banner02", @"banner01", @"banner02"];
        
        //1 顶部分类视图 图片和标题
        _categoryIVArray = @[@"icon01", @"icon02", @"icon03", @"icon04", @"icon05", @"icon06", @"icon07", @"icon08", @"icon09", @"icon10"];
        
        _categoryTitleArray = @[@"箱包用品", @"女装内衣", @"婴儿食品", @"电子产品", @"用品玩具", @"美妆个护", @"食品烟酒", @"居家百货", @"休闲娱乐", @"热门分类 "];
        
        //2 中间列表 标题名称
        _sectionArray = @[@"热门分类",@"全球购",@"奶粉纸尿裤",@"童装童鞋",@"食品烟酒",@"用品玩具",@"女装内衣",@"鞋包佩饰",@"美妆个护",@"居家百货"];
        
        
        
        //中间推荐内容
        _recommendTitleArray = @[@"热销商品"];
        _recommendImageArray = @[@"pic09", @"pic09", @"pic09", @"pic09"];
        

        
        [self goodsCategoryDataRequest];
        
        [classArray removeAllObjects];
        [self requestHomeGoodsMainData];
        
    }    
    
   

//    //刷新数据
    [_grid reloadData];
    
    
}

- (void)chooseScrollViewPicNum:(NSInteger)picNum {
    ZHomePicModel *pic = [[ZHomePicModel alloc] init];
    pic = bannerArray[picNum];
    NSString *urlStr = pic.linkUrl;//直接是商品信息
    NSLog(@"%@",urlStr);
    
    //会员商品
    if (_isGoods) {
        ZHomePicModel *pic = [[ZHomePicModel alloc] init];
        pic = bannerArray[picNum];
        //            NSString *linkStr = pic.linkUrl;
        //            NSLog(@"linkStr:%@==strlength:%d",linkStr, linkStr.length);
        if (IsNilString(pic.linkUrl)|| [pic.linkUrl isKindOfClass:[NSNull class]]) {
            NSLog(@"没有链接地址");
        }else{
            NSRange range = [pic.linkUrl rangeOfString:@"id="];
            NSString *str = [pic.linkUrl substringFromIndex:range.location+range.length];
            NSString *goodID = str;
            
            ZCommonGoodsInfoViewController *vc = [[ZCommonGoodsInfoViewController alloc] init];
            vc.comGoodsID = goodID;
            [self.navigationController pushViewController:vc animated:YES];

        }
    }
    
}

#pragma mark -- 设置字体
//展示内容 价格文字设置
- (void)setPriceTextAttributes:(NSString *)text withTableViewCell:(ZHomeGridGoodsCell *)cell {
    NSUInteger length = [text length];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:text];
    
    //最后一个字符颜色 字体大小
    [attri addAttribute:NSForegroundColorAttributeName value:HEXCOLOR(0x333333) range:NSMakeRange(length-1, 1)];
    [attri addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:9] range:NSMakeRange(length-1, 1)];
    [cell.goodsPriceLb setAttributedText:attri];
}


//展示内容 价格文字设置
- (void)setPointTextAttributes:(NSString *)text withTableViewCell:(ZHomeGridGoodsCell *)cell {
    NSUInteger length = [text length];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:text];
    
    //最后四个字符颜色 字体大小
    [attri addAttribute:NSForegroundColorAttributeName value:HEXCOLOR(0x666666) range:NSMakeRange(length-4, 4)];
    [attri addAttribute:NSFontAttributeName value:MFont(9) range:NSMakeRange(length-4, 4)];
    [cell.goodsPointsLb setAttributedText:attri];
}

#pragma mark - ===== TextFiled Delegate =====
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (IsNilString(textField.text)) {
        [SXLoadingView showAlertHUD:@"请输入搜索内容" duration:SXLoadingTime];
    }else {
        ZGoodsSearchViewController *vc = [[ZGoodsSearchViewController alloc] init];
        vc.searchStr = textField.text;
        vc.isGoods   = _isGoods;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
    [textField resignFirstResponder];
    return YES;
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (searchTF) {
        [self.view endEditing:YES];
    }
}


#pragma mark - others
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
